const router = require('koa-router')()
const { models } = require('../model')
const Excel = require('exceljs')
const { get51TalentBucketSignedUrl } = require('../utils/cos')
const { parseResume, getResumeInfo } = require('../service/resume')

router.post('/resume-upload', async function (ctx) {
  const { path, name } = ctx.request.files.file
  const fileName = name
  const matchFilter = {
    resume_file: fileName
  }
  const matchDoc = await models.ResumeParse.coll.findOne(matchFilter, {
    projection: {
      resume_file: 1
    }
  })
  if (matchDoc) {
    return ctx.wrapper.error('HANDLE_ERROR', '已存在同名简历')
  }
  // 新增简历解析
  const resumeData = await parseResume(path)
  const resumeParseDoc = {
    ...{
      resume_file: fileName
    },
    ...resumeData
  }
  const parseInsertResult = await models.ResumeParse.coll.updateOne(matchFilter, {
    $set: resumeParseDoc
  }, {
    upsert: true
  })
  const parseResultId = parseInsertResult.upsertedId._id
  const resumeInfo = await getResumeInfo(resumeParseDoc)
  if (!resumeInfo) {
    console.log(resumeParseDoc)
  }
  const resumeDoc = {
    ...resumeInfo
  }
  resumeDoc.resume_file_name = fileName
  resumeDoc.parse_results = [{
    id: parseResultId,
    platform: '小析智能'
  }]
  const resumeResult = await models.Resume.insertOne(resumeDoc)
  ctx.wrapper.succ(resumeResult)
})

router.get('/resume-excel', async function (ctx) {
  // const fileName = path.resolve(__dirname, '../data/人才库-数据模板.xlsx');
  // const workbook = new Excel.Workbook();
  // await workbook.xlsx.readFile(fileName);
  // console.log(workbook);
  const workbookProperty = {
    id: 'SystemPowerCoefficient',
    name: '简历解析数据',
    creator: '51Talent',
    worksheet: {
      columns: [
        { header: '简历解析ID', key: 'ID', width: 24 },
        { header: '跟进日志.日期时间', _h1: '跟进日志', key: 'dataNull', width: 24 },
        { header: '跟进日志.沟通方式', _h1: '跟进日志', key: 'dataNull', width: 24 },
        { header: '跟进日志.沟通所处阶段', _h1: '跟进日志', key: 'dataNull', width: 24 },
        { header: '跟进日志.类别', _h1: '跟进日志', key: 'dataNull', width: 24 },
        { header: '跟进日志.沟通内容标签', _h1: '跟进日志', key: 'dataNull', width: 24 },
        { header: '跟进日志.沟通记录', _h1: '跟进日志', key: 'dataNull', width: 24 },
        { header: '姓名', key: 'name', width: 24 },
        { header: '手机号', key: 'phone_number', width: 24 },
        { header: '微信号', key: 'wechat', width: 24 },
        { header: '邮箱', key: 'email', width: 24 },
        { header: '地址(省/自治区/直辖市)', key: 'birthplace', width: 24 },
        { header: '地址(市)', key: 'dataNull', width: 24 },
        { header: '地址(县/区)', key: 'dataNull', width: 24 },
        { header: '地址(详细地址)', key: 'detailed_location', width: 24 },
        { header: '生日', key: 'date_of_birth', width: 24 },
        { header: '备注', key: 'memo', width: 24 },
        { header: '人才顾问', key: 'dataNull', width: 24 },
        { header: '昵称', key: 'dataNull', width: 24 },
        { header: '人才标签', key: 'highlights', width: 24 },
        { header: '工作年限', key: 'num_work_experience', width: 24 },
        { header: '服务公司数', key: 'work_experience_count', width: 24 },
        { header: '性别', key: 'gender', width: 24 },
        { header: '年龄', key: 'age', width: 24 },
        { header: '生肖', key: 'dataNull', width: 24 },
        { header: '星座', key: 'dataNull', width: 24 },
        { header: '人才特质', key: 'dataNull', width: 24 },
        { header: '竞业限制', key: 'dataNull', width: 24 },
        { header: '人才状态', key: 'dataNull', width: 24 },
        { header: '授权顾问', key: 'dataNull', width: 24 },
        { header: '顾问点评', key: 'dataNull', width: 24 },
        { header: '限制条件', key: 'dataNull', width: 24 },
        { header: '操作', key: 'dataNull', width: 24 },
        { header: '沟通点数', key: 'dataNull', width: 24 },
        { header: '到面点数', key: 'dataNull', width: 24 },
        { header: '成功点数', key: 'dataNull', width: 24 },
        { header: '级别水平', key: 'professional_level', width: 24 },
        { header: '职业标签', key: 'professional', width: 24 },
        { header: '公司名称及年限', key: 'work_experience', width: 24 },
        { header: '参与过产品或项目', key: 'project_experience', width: 24 },
        { header: '从事过岗位名称及年限', key: 'dataNull', width: 24 },
        { header: '服务最大公司', key: 'dataNull', width: 24 },
        { header: '擅长技能及熟练度', key: 'predicted_skills', width: 24 },
        { header: '最高学历', key: 'degree', width: 24 },
        { header: '学校及学历', key: 'school_name', width: 24 },
        { header: '学校类型', key: 'education', width: 24 },
        { header: '外语及水平', key: 'dataNull', width: 24 },
        { header: '期望机会.省', _h1: '期望机会', key: 'dataNull', width: 24 },
        { header: '期望机会.市', _h1: '期望机会', key: 'expect_location', width: 24 },
        { header: '期望机会.岗位', _h1: '期望机会', key: 'desired_position', width: 24 },
        { header: '期望机会.年薪(万)', _h1: '期望机会', key: 'dataNull', width: 24 },
        { header: '期望机会.折算月薪', _h1: '期望机会', key: 'desired_salary', width: 24 },
        { header: '期望机会.其他说明', _h1: '期望机会', key: 'dataNull', width: 24 }
      ]
    }
  }
  const workbook = new Excel.Workbook()
  workbook.creator = workbookProperty.creator
  workbook.keywords = workbookProperty.id
  const worksheet = workbook.addWorksheet('sheet1')
  worksheet.columns = workbookProperty.worksheet.columns
  const cursor = models.Resume.find({}).limit(9999)
  let counter = 1
  for await (const doc of cursor) {
    counter++
    if (counter % 100 === 0) {
      console.log('Exporting :', counter)
    }
    doc.ID = doc.parse_results[0].id.toString()
    worksheet.addRow(doc)
  }

  // // 插入一级标题
  // worksheet.insertRow(1, ['跟进日志']);
  // worksheet.mergeCells('A1:ABK1');

  // ...

  const buffer = await workbook.xlsx.writeBuffer()
  ctx.set('Content-Type', 'application/vnd.openxmlformats')
  ctx.set('Content-Disposition', 'attachment; filename=' + encodeURIComponent('Resumes.xlsx'))
  ctx.body = buffer
})

router.get('/resume-file-download', async function (ctx) {
  const key = ctx.query.key
  const url = await get51TalentBucketSignedUrl(key)
  try {
    ctx.status = 302
    ctx.redirect(url)
  } catch (e) {
    throw e.toString()
  }
})

router.post('/resume/actions/findPages', async function (ctx) {
  const pagination = ctx.paginationResolve()
  const findQuery = {}
  const docCount = await models.Resume.countDocuments(findQuery)
  const docs = await models.Resume
    .find(findQuery)
    .project({ source: 0 })
    .sort({ updatedAt: -1 })
    .skip(pagination.offset)
    .limit(pagination.limit)
    .toArray()
  ctx.wrapper.succ({
    rows: docs,
    total: docCount
  })
})

router.post('/resume/actions/deleteById', async function (ctx) {
  const { id } = ctx.request.body
  const oldDoc = await models.Resume.findById(id)
  if (!oldDoc) {
    return ctx.wrapper.error('NULL_ERROR', '无对应 ID 资源')
  }
  const resumeParseIds = oldDoc.parse_results.map(e => e.id)
  for (const resumeParseId of resumeParseIds) {
    await models.ResumeParse.deleteById(resumeParseId)
  }
  const result = await models.Resume.deleteById(id)
  ctx.wrapper.succ(result)
})

module.exports = router
